package com.suredy.app.porject.ctrl.flow;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.suredy.app.porject.constants.FlowStatus;
import com.suredy.app.porject.model.Bid;
import com.suredy.app.porject.model.Contract;
import com.suredy.app.porject.model.FlowOfBid2User;
import com.suredy.app.porject.model.FlowOfContract2User;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.security.entity.UserEntity;
import com.suredy.security.service.RoleSrv;
import com.suredy.security.service.User2RoleSrv;

/**
 * 招标管理流程控制器
 * 
 * @author VIVID.G
 * @since 2015-12-25
 * @version v0.1
 */
public class FlowCtrl extends BaseCtrl {

	@Autowired
	protected RoleSrv roleSrv;

	@Autowired
	protected User2RoleSrv user2RoleSrv;

	protected FlowOfBid2User createBidFlowInfo(Bid bid, UserEntity user, FlowStatus status) {
		if (bid == null || user == null || StringUtils.isBlank(user.getId()))
			throw new IllegalArgumentException("Invalid param Bid[bid] or UserEntity[user]");

		FlowOfBid2User flow = new FlowOfBid2User();

		flow.setBid(bid);
		flow.setUser(user);
		flow.setStatus(status);
		flow.setActive(true);
		flow.setTime(new Date());

		if (bid.getFlowInfo() == null)
			bid.setFlowInfo(new ArrayList<FlowOfBid2User>());

		bid.getFlowInfo().add(flow);

		return flow;
	}

	protected FlowOfContract2User createContractFlowInfo(Contract contract, UserEntity user, FlowStatus status) {
		if (contract == null || user == null || StringUtils.isBlank(user.getId()))
			throw new IllegalArgumentException("Invalid param Bid[bid] or UserEntity[user]");

		FlowOfContract2User flow = new FlowOfContract2User();

		flow.setContract(contract);
		flow.setUser(user);
		flow.setStatus(status);
		flow.setActive(true);
		flow.setTime(new Date());

		if (contract.getFlowInfo() == null)
			contract.setFlowInfo(new ArrayList<FlowOfContract2User>());

		contract.getFlowInfo().add(flow);

		return flow;
	}

	/**
	 * 通过角色获取用户
	 * 
	 * @param roleCodes
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<UserEntity> getUserByRoles(String... roleCodes) {
		if (roleCodes == null || roleCodes.length <= 0)
			return null;

		String ql = "SELECT DISTINCT NEW UserEntity(T.user.id, T.user.name) FROM User2RoleEntity T LEFT JOIN T.role R WHERE R.code IN (";

		for (int i = 0; i < roleCodes.length; i++) {
			ql += ",?";
		}

		ql += ")";

		ql = ql.replaceFirst("\\(,", "(");

		List<UserEntity> ret = (List<UserEntity>) this.user2RoleSrv.readByQL(ql, (Object[]) roleCodes);

		if (ret == null || ret.isEmpty())
			return null;

		return ret.isEmpty() ? null : ret;
	}

}
